import base64
import os
from datetime import datetime
from hashlib import md5
from io import BytesIO
from pathlib import Path
from typing import Union

from fastapi import UploadFile as File

from app.core.helpers import upload_file_path
from app.core.responses import Response


class UploadServices:
    allow_type = ['.gif', '.jpg', '.jpeg', '.png','mp4']
    path = f'./storage/images'

    def __init__(self, file: Union[File, str], file_format=None, path_file: str = path):
        if file_format is None:
            file_format = self.allow_type
        self.file = file
        self.allow_type = file_format
        self.path_file = path_file

    @staticmethod
    def randName(ext: str):
        return f"{md5(datetime.now().strftime('%Y-%m-%d %H:%M:%S').encode()).hexdigest()}{ext}"

    def verifyFile(self):
        if not self.file:
            return {'上传文件为空！'}
        ext = Path(self.file.filename).suffix
        print(format(ext), self.allow_type)
        if ext in self.allow_type:
            return True
        return {'文件格式错误'}

    async def createFile(self):
        if self.verifyFile():
            file = self.file
            ext = Path(file.filename).suffix
            filename = self.randName(ext=ext)
            if not os.path.exists(self.path):
                os.mkdir(self.path)
            file_path = os.path.join(self.path, filename)
            f = open(file_path, 'wb')
            data = await file.read()
            print(data)
            f.write(data)
            f.close()
            # 'file_path': file_path, 'url': upload_file_path(file_path),
            return [{'url':file_path}]
        return self.verifyFile()

    async def createBase64File(self, ext: str):
        file = self.file
        image_data = base64.b64decode(file.split(',')[1])
        filename = self.randName(ext=ext)
        if not os.path.exists(self.path):
            os.mkdir(self.path)
        file_path = os.path.join(self.path, filename)
        with open(file_path, "wb") as f:  # 将图片数据写入文件
            f.write(image_data)
        with open(file_path, "rb") as f:
            data = f.read()
        print(data)
        f.close()
        return {'file_path': file_path, 'url': upload_file_path(file_path), 'file': data}
